import {EventEmitter, Injectable} from '@angular/core';
import {Http, RequestOptions} from "@angular/http";
import MTSConstants from "../config/config";
import {BackCode} from "../model/backCode";
import {Vehicle} from "../model/vehicle";
import {Condition} from "../model/condition";
import {Application} from "../model/application";

@Injectable()
export class CamSearchService {
  servicename:string;
  change: EventEmitter<Condition>;
  userChange:EventEmitter<string>;  //单选人员开窗
  constructor(private http:Http) {
    this.change = new EventEmitter();
    this.userChange = new EventEmitter();
  }

  //用车信息查询
  getCamApplyInfo(pageNumber:number,pageSize:number,userId:string,phase:string,vehiclename:string,vehicleoid:string,status:string){
    const url = `${MTSConstants.HOSTUser}applications/?pageNumber=${pageNumber}&pageSize=${pageSize}&userId=${userId}&phase=${phase}&vehiclename=${vehiclename}&vehicleoid=${vehicleoid}&exclude=${status}`;
    // console.log(url);
    return this.http.get(url)
      .toPromise()
      .then(res=>{return res.json()})
      .catch((error: any) => {return this.handleError('getCamApplyInfo',error);});
  }

  //判断当前登录者是否是车辆管理员

  checkUser(userid:string):Promise<BackCode>{
    const url = `${MTSConstants.HOSTUser}openwin/group/user/${userid}`;
    const headers = MTSConstants.headers;//spring的restful接口用这个
    const options = new RequestOptions({ headers: headers });
    return this.http.get(url,options)
      .toPromise()
      .then((res) => { return res.json() as BackCode;})
      .catch((error: any) => {return this.handleError('checkUser',error);});
  }


  //查询车辆信息
  getVehicles():Promise<Vehicle[]>{
    const url = `${MTSConstants.HOSTUser}vehicles`;
    return this.http.get(url)
      .toPromise()
      .then((res) => { return res.json()})
      .catch((error: any) => {return this.handleError('getVehicles',error);});
  }

  //用车申请信息删除
  delApplication(oid:string):Promise<BackCode>{
    const url = `${MTSConstants.HOSTUser}application/${oid}`;
    const headers = MTSConstants.headers;//spring的restful接口用这个
    const options = new RequestOptions({ headers: headers });
    return this.http.delete(url, options)
      .toPromise()
      .then((res) => { return res.json() as BackCode;})
      .catch((error: any) => {return this.handleError('deleteRoom',error);});
  }


  //用车申请取消
  cancelApplication(processsn:string):Promise<BackCode>{
    const url = `${MTSConstants.HOSTUser}application/return/abort?processsn=${processsn}`;
    const headers = MTSConstants.headers;//spring的restful接口用这个
    return this.http.post(url,headers)
      .toPromise()
      .then((res) => { return res.json() as BackCode;})
      .catch((error: any) => {return this.handleError('cancelApplication',error);});
  }

  handleError(functionName:string,error: any): Promise<any> {
    console.error(`服务 : ${this.servicename} , 函数 : ${functionName} 。发生错误 : `, error);
    return Promise.reject(error.message || error);
  }
}
